package com.haople.sso.ram.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

import com.haople.sso.core.util.Md5;
import com.haople.sso.core.vo.Ticket;

public class RAMUtil {

	private  static final Logger logger=Logger.getLogger(RAMUtil.class);
	/**
	 * map : k 为 userId
	 * 		 v 为  票据对象
	 */
	private static final Map<String, Ticket> MAP=new ConcurrentHashMap<String, Ticket>();
	
	/**
	 * 将票据放于内存中
	 * @param ticket
	 */
	public static boolean put(Ticket ticket) throws Exception{
		boolean flag=false;
		try {
			if(ticket==null){
				throw new NullPointerException("---将票据加入内存中时--票据ticket is null---返回---");
			}
			if(ticket.getUserId()==null || ticket.getUserId().equals("")){
				throw new NullPointerException("---将票据加入内存中时--userName is null---返回---");
			}
			//作为key值存储
			MAP.put(Md5.md5(ticket.getUserId()), ticket); 
			flag=true;
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return flag;
	}
	
	/**
	 * 在内存中获取票据
	 * @param ticket
	 * @return
	 */
	public static Ticket get(String userId) throws Exception{
		try {
			if(userId==null || userId.equals("")){
				throw new NullPointerException("---在内存中获取票据时--userName is null---返回---");
			}
			return MAP.get(Md5.md5(userId));
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return null;
		}
	}
}
